<?php

abstract class Importer{
	
	/* PATHS */
	const PATH_CONFIG_FOLDER = '/var/www/futbol/protected/importers/configs/';
	const PATH_XML_FOLDER = '/var/www/futbol/protected/importers/xml/';
	const PATH_LOGS_FOLDER = '/var/www/futbol/protected/importers/logs/';
	
	/* FEEDERS */
	const FEEDER_NAME_WH = 'WH';							/* William Hill */
	
	protected $xml = null;
	protected $config = null;
	protected $feeder = null;
	protected $league = null;
	protected $oddType = null;
	protected $currentJourney  = null;
	protected $currentSeason = null;
	protected $leagueTeams = null;
	
	protected $errorCount = 0;
	
	public function runImportation(){
		$this->execute();
		$this->endImportation();
	}
	
	public function prepareImportation( $feeder, $league, $oddType ){
		Yii::import("application.models.*", true);
	
		/* Pre begin importation */
		$this->beginImportation();
		
		/* Get data feed & save XML file */
		$this->getDataFeed();
	
		/* Loaf configuration and XML */
		$this->loadConfig();
		$this->loadXML();
	
		$this->feeder = $feeder;
		$this->league = Leagues::model()->findByPk( $league );
		$this->oddType = OddTypes::model()->findByPk( $oddType );
	
		/* Invalid league code */
		if( !$this->league || !isset( $this->config[ $league ] ) ){
			echo "Error. Check Log.\n";
			$this->errorCount++;
			$this->insertLog( "Error executing command: '$league' not recognized as league code in own config.\n" );
			exit;
		}
	
		/* Invalid bet type */
		if( !$this->oddType || !isset( $this->config[ $league ][ 'betTypes' ][ $oddType ] ) ){
			echo "Error. Check Log.\n";
			$this->errorCount++;
			$this->insertLog( "Error executing command: '$oddType' not recognized as bet type in own config.\n" );
			exit;
		}
	
		$this->loadCurrentJourney();
		$this->loadCurrentSeason();
		$this->loadTeamsByLeagueSeason();
	}
	
	abstract public function execute();
	
	public function beginImportation(){
		$this->insertLog( "\n\n\n------------------------------------------------", false );
		$this->insertLog( "\n* Importation begin ". date( 'Y-m-d H:i:s' ), false );
		$this->insertLog( "\n------------------------------------------------\n\n", false );
	}
	
	public function endImportation(){
		if( $this->count == 0 ) $this->insertLog( "0 error(s) found\n" );
		$this->insertLog( "\n------------------------------------------------", false );
		$this->insertLog( "\n* Importation end ". date( 'Y-m-d H:i:s' ), false );
		$this->insertLog( "\n------------------------------------------------\n\n", false );
		
		if( $this->count > 0 )
			echo "\nImportation has been completed. $this->errorCount error(s) found. Check ".static::LOG_NAME.".log\n\n";
		else
			echo "\nImportation has been completed wtih no errors.\n\n";
		unlink( self::PATH_XML_FOLDER.static::XML_NAME.'.xml' );
	}
	
	public function getDataFeed(){
		if( file_exists( self::PATH_XML_FOLDER.static::XML_NAME.'.xml' ) ){
			// If file exists, don't import anything, something wrong with last importation
			echo "Error. Check Log.\n";
			$this->errorCount++;
			$this->insertLog( "File '" . static::XML_NAME . ".xml' already exists.\n" );
			exit;
		}else{
			try{
				file_put_contents( self::PATH_XML_FOLDER.static::XML_NAME.'.xml', file_get_contents( static::URL_FEED ) );
			}catch( \Exception $e ){
				echo "Error. Check Log.\n";
				$this->errorCount++;				
				$this->insertLog( "Error reading feed: {$e->getMessage()}" );
				exit;
			}
		}
	}
	
	public function loadXML(){
		$this->xml = new SimpleXMLElement( file_get_contents( self::PATH_XML_FOLDER.static::XML_NAME.'.xml' ) );
	}
	
	public function loadConfig(){
		$this->config = (include self::PATH_CONFIG_FOLDER.static::CONFIG_NAME.'.php');
	}
	
	public function loadCurrentJourney(){
		$this->currentJourney = Journeys::model()->findByAttributes( array( 'current' => 1 ) );
	}
	
	public function loadCurrentSeason(){
		$this->currentSeason = Seasons::model()->findByAttributes( array( 'current' => 1 ) );
	}
	
	public function loadTeamsByLeagueSeason(){
		$this->leagueTeams = TeamsSeasonsLeagues::getTeamsByLeagueSeason( $this->currentSeason->idSeason, $this->league->idLeague );
	}
	
	public function getTeamsIdByTeamName( $teamName ){
		foreach( $this->config[ $this->league->idLeague ]['teams'] as $idTeam => $name ){
			if( $name == $teamName ) return $idTeam;
		}
		return false;
	}
	
	public function insertLog( $log, $withDate = true ){
		$log == $withDate ?  date( 'Y-m-d H:i:s' ).' '.$log : $log;
		file_put_contents( self::PATH_LOGS_FOLDER.static::LOG_NAME.'.log', $log, FILE_APPEND );
	}
	
}